package org.exteen.tag.core;

import org.exteen.ExteenException;
import org.exteen.exec.ExteenContext;
import org.exteen.exec.Tag;
import org.exteen.lib.DynamicTagLibrary;
import org.exteen.output.ExteenStream;
import org.exteen.parser.Node;

public class TaglibTag extends Tag {

    public void doTag(ExteenContext ctx, ExteenStream stream) {

        Object uri = ctx.getVarAttrValue("uri");
        if (uri==null) {
            throw new ExteenException("Required attribute 'uri' missing or null");
        }

        DynamicTagLibrary library = new DynamicTagLibrary(uri.toString());
        ctx.getParent().addLibrary(library);
        // only d:tag allowed
        for (Object o: ctx.getNode().getChildren()) {
            if (o instanceof Node) {
                Node child = (Node) o;
                Tag tag = ctx.getTagForNode(child);
                if (tag!=null && tag instanceof TagTag) {
                    Object name = ctx.getVarAttrValue(child.getAttribute("name"));
                    if (name==null) {
                        throw new ExteenException("Attribute name is missing for tag tag");
                    }
                    library.addTag(name.toString(), child);
                } else if (!(tag instanceof TagTag)) {
                    throw new ExteenException(child.getFullTag() + " not allowed inside taglib");
                }
            }
        }
    }
}